package com.loong.android.utils;

import android.content.Context;
import java.lang.reflect.Field;

/**
 * 资源id工具类
 */
public class ResourceIdUtils {
    private static final String TAG = ResourceIdUtils.class.getSimpleName();
    private static ResourceIdUtils instance;

    public static ResourceIdUtils getInstance() {
        if (instance == null) {
            instance = new ResourceIdUtils();
        }
        return instance;
    }

    private Class<?> getCla(Context context, String resClassName) {
        Class<?> cla = null;
        try {
            cla = Class.forName(context.getApplicationContext().getPackageName() + resClassName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return cla;
    }

    public int getDrawableId(Context context, String resName) {
        return getResId(getCla(context, ".R$drawable"), resName);
    }

    public int getLayoutId(Context context, String resName) {
        return getResId(getCla(context, ".R$layout"), resName);
    }

    public int getIdId(Context context, String resName) {
        return getResId(getCla(context, ".R$id"), resName);
    }

    public int getAnimId(Context context, String resName) {
        return getResId(getCla(context, ".R$anim"), resName);
    }

    public int getStyleId(Context context, String resName) {
        return getResId(getCla(context, ".R$style"), resName);
    }

    public int getStringId(Context context, String resName) {
        return getResId(getCla(context, ".R$string"), resName);
    }

    public int getArrayId(Context context, String resName) {
        return getResId(getCla(context, ".R$array"), resName);
    }

    public int getIdFromMipmap(Context context, String resName) {
        return getResId(getCla(context, ".R$mipmap"), resName);
    }

    public int getIdFromStyleable(Context context, String resName) {
        return getResId(getCla(context, ".R$styleable"), resName);
    }

    /**
     * 取任意R类的子类的资源id
     * @param context 上下文
     * @param className R类的内嵌类的路径，如: ".R$string"
     * @param resName 资源名称
     */
    public int getIdFrom(Context context, String className, String resName) {
        return getResId(getCla(context, className), resName);
    }

    private int getResId(Class<?> resClass, String resName) {
        if (resClass == null) return -1;
        try {
            Field field = resClass.getField(resName);
            return field.getInt(resName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }
}
